<!doctype html>
<html>

	<head>
		<meta charset="utf-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<meta http-equiv="Content-Type" content="multipart/form-data; charset=utf-8" />
		<link href="css/mui.css" rel="stylesheet" />
		<style>
			        
        /*这里的样式是为第一个行的单选框写的,其他的换行的不用*/
          .radio_inline{
                display: inline-block;
                width: 65%;
            }
            .radio_inline label{

                width: 20%;
                padding-left: 40px;
                padding-right: 40px;
            }
            .radio_inline input[type=radio]{
                width: 15%;             
                right: auto;
            }
            
            
            /*//换个样式*/
           .change .mui-radio input[type='radio']:checked:before{
            content:'\e442';
            color:red;
            }
        </style>
	</head>

	<body>
		<script src="js/mui.js"></script>
		<script src="js/app.js"></script>
		<script type="text/javascript">
			mui.init({
			  pullRefresh : {
				container:"#refreshContainer",//下拉刷新容器标识，querySelector能定位的css选择器均可，比如：id、.class等
				down : {
				  style:'circle',//必选，下拉刷新样式，目前支持原生5+ ‘circle’ 样式
				  color:'#2BD009', //可选，默认“#2BD009” 下拉刷新控件颜色
				  height:'50px',//可选,默认50px.下拉刷新控件的高度,
				  range:'100px', //可选 默认100px,控件可下拉拖拽的范围
				  offset:'0px', //可选 默认0px,下拉刷新控件的起始位置
				  auto: true,//可选,默认false.首次加载自动上拉刷新一次
				  callback :csh() //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
				}
			  }
			});
			
			function add0(m){return m<10?'0'+m:m }
			function formatTime(shijianchuo){
				//shijianchuo是整数，否则要parseInt转换
				var time = new Date(shijianchuo);
				var y = time.getFullYear();
				var m = time.getMonth()+1;
				var d = time.getDate();
				var h = time.getHours();
				var mm = time.getMinutes();
				var s = time.getSeconds();
				return y+'-'+add0(m)+'-'+add0(d);
			}
			
			/*'yyyy-MM-dd'格式的字符串转日期*/
			function stringToDate(str){
				var dateStrs = str.split("-");
				var year = parseInt(dateStrs[0], 10);
				var month = parseInt(dateStrs[1], 10) - 1;
				var day = parseInt(dateStrs[2], 10);
				var date = new Date(year, month, day);
				return date;
			}
			
			function csh(){
				var a = localStorage.getItem("account");
				
				mui.ajax(ip+'/user/getInfo?name='+a,{
				dataType:'json',//服务器返回json格式数据
				type:'get',//HTTP请求类型
				timeout:10000,//超时时间设置为10秒；
				headers:{'Content-Type':'application/x-www-form-urlencoded'},
				success:function(data){
					var uname = document.getElementById("uname");
					var imgSrc = document.getElementById("img_src");
					var age = document.getElementById("age");
					var tel = document.getElementById("tel");
					var province = document.getElementById("tz");
					var city = document.getElementById("sg");
					var address = document.getElementById("dz");
					
					if("undefined" == typeof data.name){ 
						data.name = "";
					}
					if("undefined" == typeof data.img){ 
						data.img = "";
					}
					if("undefined" == typeof data.age){
						data.age = "";
					}
					if("undefined" == typeof data.phone){ 
						data.phone = "";
					}
					if("undefined" == typeof data.province){ 
						data.province = "";
					}
					if("undefined" == typeof data.city){ 
						data.city = "";
					}
					if("undefined" == typeof data.address){
						data.address = "";
					}
					
					uname.value = data.name;
					tel.value = data.phone;
					imgSrc.src = ip+"/file/"+data.img+".png";
					age.value = data.age;
					province.value = data.province;
					city.value = data.city;
					address.value = data.address;

				},
				error:function(xhr,type,errorThrown){
					//异常处理；
					mui.toast("服务器错误！");
					return 0;
				}
				});
			}
			
			function upWd(){
				var a = localStorage.getItem("account");
				console.log("修改个人信息")
				var imgSrc = document.getElementById("img_src");
				var age = document.getElementById("age").value;
				var tel = document.getElementById("tel").value;
				var province = document.getElementById("tz").value;
				var city = document.getElementById("sg").value;
				var address = document.getElementById("dz").value;
				var str = '';
				console.log(imgSrc.src);
				str = imgSrc.src.split("file")[1].split("png")[0];
				str = str.substring(1, str.length -1);
				console.log(str);

				var url = "?name="+a;
				url += "&"+"phone="+tel;
				url += "&"+"img="+str;
				url += "&"+"age="+age;
				url += "&"+"province="+province;
				url += "&"+"city="+city;
				url += "&"+"address="+address;
				
				console.log(url)
				mui.ajax(ip+'/user/updateUser'+url,{
				dataType:'json',//服务器返回json格式数据
				type:'get',//HTTP请求类型
				timeout:10000,//超时时间设置为10秒；   
				headers:{'Content-Type':'application/x-www-form-urlencoded'},
				success:function(data){
					mui.toast("修改成功");
				},
				error:function(xhr,type,errorThrown){
					//异常处理；
					mui.toast("修改成功");
					return 0;
				}
				});
			}
			
			function getRadioValue(className){
				var cks = document.getElementsByClassName(className);
				var val = null;
				for(i=0; i<cks.length; i++){
					if(cks[i].checked){
						val = cks[i].value;
					}
				}
				return val;
			}
			
			mui.plusReady(function(){
			    document.getElementById('userImg').addEventListener('tap',function(){
			        if(mui.os.plus){
			            var a=[{
			                title:'拍照'
			            },{
			                title:'从手机相册选择'
			            }];
			            plus.nativeUI.actionSheet({
			                title:'修改头像',
			                cancel:'取消',
			                buttons:a
			            },function(b){
			                switch(b.index){
			                    case 0:
			                        break;
			                    case 1:
			                        //拍照
			                        getImages();
			                        break;
			                    case 2:
			                        //打开相册
			                        galleryImages();
			                        break;
			                    default:
			                        break;
			                }
			            },false);   
			        }
			    });
			
			    //拍照
			    function getImages(){
			        var mobileCamera=plus.camera.getCamera();
			        mobileCamera.captureImage(function(e){
			            plus.io.resolveLocalFileSystemURL(e,function(entry){
			                var path=entry.toLocalURL()+'?version='+new Date().getTime();
			                uploadHeadImg(path);
			            },function(err){
			                console.log("读取拍照文件错误");
			            });
			        },function(e){
			            console.log("er",err);
			        },function(){
			            filename:'_doc/head.png';
			        });
			    }
			
			    //从本地相册选择
			    function galleryImages(){
			        console.log("你选择了从相册选择");
			       // 从相册中选择图片
			           plus.gallery.pick( function(e){
			               // 从选择的最后一张照片开始到选择的第一张倒叙循环输出
			               for(var i in e.files){
			                   var fileSrc = e.files[i];
			                   uploadHead(fileSrc)
			               }
			           }, function ( e ) {
			               mui.toast( "您取消了选择图片" );
			           },{
			               filter: "image",
			               multiple: true,
			               maximum: 6,
			               system: false,
			               onmaxed: function() {
			                   plus.nativeUI.alert('最多只能选择6张图片');
			               }
			           });
			    };
			//上传头像图片 
			var width = 0; 
			var height = 0;
			function uploadHead(imgPath){ 
				console.log(imgPath)
				
			    var image = new Image(); 
			    image.src = imgPath; 
			    image.onload = function(){
			        width=800;
			        var height1=image.width/800;
			        height=image.height/height1;
			        var imgData = getBase64Image(image);
			        mui.ajax(ip+"/uploadPhoto", { 
			            data: { 
			                 imgBase64:imgData
			            }, 
			            dataType: 'json', 
			            type: 'post', 
			            timeout: 10000,             
			            success: function(data){ 
							var mainImg=document.getElementById('img_src');
							mainImg.src=ip+"/file/"+data.src+".png";
							console.log(mainImg.src);
			                console.log(data.src)
			            }, 
			            error: function(xhr, type, errorThrown){ 
							console.log(xhr);
							console.log(type);
							console.log(errorThrown);
			                mui.toast('网络异常，请稍后再试！'); 
			            } 
			        });
			    } 
			} 
			//将图片压缩转成base64 
			function getBase64Image(img) { 
			    var canvas = document.createElement("canvas"); 
			    //压缩图片
			    // calculate the width and height, constraining the proportions 
			     /*if (width > height) { 
			        if (width > 800) { 
			            height = Math.round(height *= 800 / width); 
			            width = 800; 
			        } 
			    } else { 
			        if (height > 800) { 
			            width = Math.round(width *= 800 / height); 
			            height = 800; 
			        } 
			    }*/
			    canvas.width = width;   
			    canvas.height = height; 
			    var ctx = canvas.getContext("2d"); 
			    ctx.drawImage(img, 0, 0, width,height); /*绘图*/ 
			    var dataURL = canvas.toDataURL("image/png", 0.8); 
			    //return dataURL.replace("data:image/png;base64,", "");
			    return dataURL;
			}    
			    //上传图片
			    function uploadHeadImg(imgPath){
			        //选中图片之后，头像当前的照片变为选择的照片
			        var mainImg=document.getElementById('userImg');
			        mainImg.src=imgPath;
			
			
			        var images=new Image();
			        images.src=imgPath;
			        // var imgData=getBase64Image(images);
					var imgData = imgPath;
			        mui.ajax(ip + '/upload',{
			            data:{
			                'file':imgData
			            },
			            dataType:'json',//服务器返回json格式数据
			            type:'post',//HTTP请求类型
			            timeout:10000,//超时时间设置为10秒；
			            success:function(data){
			                if(data.status=='1'){
			                    mui.alert('上传成功！');
			                }
			            },
			            error:function(xhr,type,errorThrown){
			                if(type=='timeout'){
			                    mui.alert('服务器连接超时，请稍后再试');
			                }   
			            }
			        });
			    }
			
			
			    //压缩图片转成base64
			    function getBase64Image(img){
			        var canvas=document.createElement("canvas");
			        var width=img.width;
			        var height=img.height;
			        if(width>height){
			            if(width>100){
			                height=Math.round(height*=100/width);
			                width=100;
			            }
			        }else{
			            if(height>100){
			                width=Math.round(width*=100/height);
			            }
			            height=100;
			        }
			
			        canvas.width=width;
			        canvas.height=height;
			        var ctx=canvas.getContext('2d');
			        ctx.drawImage(img,0,0,width,height);
			
			        var dataUrl=canvas.toDataURL('image/png',0.8);
			        return dataUrl.replace('data:image/png:base64,','');
			    }   
			});
		</script>

		<header class="mui-bar mui-bar-nav">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
			<h1 class="mui-title">个人信息维护</h1>
		</header>

		<form class="mui-input-group" style="margin-top: 50px;" enctype="multipart/form-data">
			<div class="mui-table-view-cell infoName">
			    <a class="mui-navigate-right" id="userImg"  href="#">头像</a>
			    <img class="userImg" id="img_src" src="../file/994a60c4-e8db-4fc6-b1de-e4c1c77fb604.png" />
			</div>
			<div class="mui-input-row">
				<label>姓名</label>
				<input type="text" class="mui-input-clear" placeholder="请输入姓名" id="uname" disabled="disabled">
			</div>
			<div class="mui-input-row">
				<label>年龄</label>
				<input type="text" class="mui-input-clear" placeholder="请输入年龄" id="age">
			</div>
			<div class="mui-input-row">
				<label>电话</label>
				<input type="text" class="mui-input-clear" placeholder="请输入电话" id="tel">
			</div>
			<div class="mui-input-row">
				<label>地址</label>
				<input type="text" class="mui-input-clear" placeholder="请输入地址" id="dz">
			</div>
			<div class="mui-input-row">
				<label>体重</label>
				<input type="text" class="mui-input-clear" placeholder="请输入体重" id="tz">
			</div>
			<div class="mui-input-row">
				<label>身高</label>
				<input type="text" class="mui-input-clear" placeholder="请输入身高" id="sg">
			</div>
			<div class="mui-button-row">
				<button type="button" class="mui-btn mui-btn-primary" onclick="upWd();">确认修改</button>
			</div>
		</form>

	</body>
</html>
